package com.example.demo.domain;

import javax.persistence.*;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Entity //1
//@NamedQuery(name = "Resource.nameQuery",
//        query = "select r from Resource r where r.name=?1 ")
@Table(name = "resource",indexes = {@Index(name = "parent",columnList = "Parent"),@Index(name = "user_id",columnList = "user_id")})//,uniqueConstraints = {@UniqueConstraint(name = "parent",columnNames = {"Parent"})
public class Resource {
    @Id //2
    @GeneratedValue(strategy = GenerationType.IDENTITY) //3
    private Long id;

    private String Name;

    private Date CreateTime;

    private long Downloads;

    private long Views;

    private int Level;

    private int Score;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "user_id",foreignKey = @ForeignKey(name = "FK_Resource_User")) // 在多端（从表的外键）添加外键字段指向一端（主表的主键）的主键字段
    private User user;
//
    @ManyToOne(cascade=CascadeType.MERGE)
    @JoinColumn(name = "Parent",foreignKey = @ForeignKey(name = "Parent_Child")) // 在多端（从表的外键）添加外键字段指向一端（主表的主键）的主键字段
    private Resource Parent;

    @OneToMany(mappedBy="Parent", cascade=CascadeType.REMOVE, fetch=FetchType.LAZY)
    public List<Resource> Childs;


//    @ManyToMany(mappedBy = "Resources")
//    private Set<Person> persons;

    public Resource(){}

    public Resource(String name, Date createTime) {
        Name = name;
        CreateTime = createTime;
    }

    public HashMap<String,String> ToArray(){
        HashMap<String,String >  res = new HashMap<>();
        res.put("id",id.toString());
        res.put("name",Name);
        res.put("createtime",CreateTime.toString());
        res.put("downloads", String.valueOf(Downloads));
        res.put("views",String.valueOf(Views));
        res.put("level",String.valueOf(Level));
        res.put("parentname",Parent==null?null:Parent.Name);
        return res;
    }

    public Resource getParent() {
        return Parent;
    }

    public void setParent(Resource parent) {
        Parent = parent;
    }

    public List<Resource> getChilds() {
        return Childs;
    }

    public void setChilds(List<Resource> childs) {
        Childs = childs;
    }

    public Long getId() {
        return id;
    }

    public String getName() {
        return Name;
    }

    public void setName(String name) {
        Name = name;
    }

    public long getViews() {
        return Views;
    }

    public void setViews(long views) {
        Views = views;
    }

    public int getLevel() {
        return Level;
    }

    public void setLevel(int level) {
        Level = level;
    }

    public long getDownloads() {
        return Downloads;
    }

    public void setDownloads(long downloads) {
        Downloads = downloads;
    }

    public int getScore() {
        return Score;
    }

    public void setScore(int score) {
        Score = score;
    }
}
